<?php
/**
 * Created by PhpStorm.
 * User: xiao
 * Date: 2017/6/30
 * Time: 上午10:39
 */

namespace app\src\withdrawDeposit\logic;


use app\src\account\enmu\AccountEnmu;
use app\src\accountScore\logic\AccountScoreLogic;
use app\src\base\helper\ConfigHelper;
use app\src\base\logic\BaseLogic;
use app\src\message\config\MessageConfig;
use app\src\message\facade\MessageEntity;
use app\src\message\sms\JuheSms;
use app\src\platform\logic\PlatformLogic;
use app\src\seller\logic\SellerLogic;
use app\src\user\logic\VUserInfoLogic;
use app\src\withdrawDeposit\model\WithdrawDeposit;
use think\Db;
use think\Exception;

class WithdrawDepositLogic extends BaseLogic
{
    protected function _init()
    {
        $this->setModel(new WithdrawDeposit());
    }

    /**
     * 添加提现申请
     * @param $type
     * @param $account_id
     * @param $score
     * @param $apply_info
     * @return array
     */
    public function addApply($type, $account_id, $score, $apply_info)
    {
        if(!in_array($type, [AccountEnmu::USER, AccountEnmu::PLATFORM, AccountEnmu::SELLER])){
            return $this->apiReturnErr('type error');
        }

        if($score <= 0) return $this->apiReturnErr('提现积分必须大于0');

        $c = ConfigHelper::getValue('WITHDRAW_LIMIT');
        //提现限制检测
        if(!is_null($c)) {
            if (isset($c[$type]) && $c[$type] > $score) {
                return $this->apiReturnErr('提现金额不能少于'.$c[$type]);
            }
        }

        //提现申请检测
        $map = [
            'type' => $type,
            'account_id' => $account_id,
            'apply_status' => 0,
            'status' => 0
        ];
        $result = $this->count($map);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $count = $result['info'];
        $max = 0;
        if($count > $max) return $this->apiReturnErr('已经有超过'.($max+1).'条的提现记录，请等待客服处理完毕后再申请!');

        //判断账号信息
        $result = (new AccountScoreLogic)->getScore($type, $account_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        //判断可提现积分是否足够
        $account_score = $result['info'];
        if($account_score['score1'] < $score) return $this->apiReturnErr('剩余积分小于提现积分，无法申请提现');

        $entity = [
            'type' => $type,
            'account_id' => $account_id,
            'create_time' => NOW_TIME,
            'update_time' => NOW_TIME,
            'score' => $score,
            'apply_info' => json_encode($apply_info, JSON_UNESCAPED_UNICODE),
            'apply_status' => 0,
            'status' => 0
        ];

        $result = $this->add($entity);
        if($result['status']){
            return $this->apiReturnSuc('success');
        }else{
            return $this->apiReturnErr($result['info']);
        }

    }

    /**
     * 获取提现申请信息
     * @param $apply_id
     * @return array
     */
    public function getApplyInfo($apply_id)
    {
        $map = [
            'id' => $apply_id,
            'status' => 0
        ];
        $result = $this->getInfo($map);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('error apply');

        $apply_info = $result['info'];
        //获取提现人信息 个人 平台 商家
        $type = $apply_info['type'];
        $account_id = $apply_info['account_id'];
        $apply_name = '未知';
        switch ($type){
            case AccountEnmu::USER:
                $map = ['id' => $account_id];
                $result = (new VUserInfoLogic)->getInfo($map);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                if(empty($result['info'])) return $this->apiReturnErr('error applier');
                $apply_name = $result['info']['nickname'];
                break;
            case AccountEnmu::PLATFORM:
                $result = (new PlatformLogic)->getPlatformInfo($account_id);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                $apply_name = $result['info']['name'];
                break;
            case AccountEnmu::SELLER:
                $result = (new SellerLogic)->getSellerInfo($account_id);
                if(!$result['status']) return $this->apiReturnErr($result['info']);
                $apply_name = $result['info']['name'];
                break;
        }
        $apply_info['apply_name'] = $apply_name;

        return $this->apiReturnSuc($apply_info);

    }

    /**
     * 通过提现申请
     * @param $apply_id
     * @return array
     */
    public function passApply($apply_id)
    {
        $result = $this->getApplyInfo($apply_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $apply_info = $result['info'];

        Db::startTrans();
        try{
            $entity = [
                'apply_status' => 1,
                'update_time' => NOW_TIME
            ];

            $result = $this->saveByID($apply_id, $entity);

            if(!$result['status']){
                Db::rollback();
                return $this->apiReturnErr($result['info']);
            }

            $reason = '提现减少积分';

            //减少积分
            $result = (new AccountScoreLogic)->minusScore($apply_info['type'], $apply_info['account_id'], AccountScoreLogic::SCORE_TYPE_1, $apply_info['score'], $reason);
            if(!$result['status']){
                Db::rollback();
                return $this->apiReturnErr($result['info']);
            }

            Db::commit();
            $info = json_decode($apply_info['apply_info'],true);
            $score = $apply_info['score']/100;

            $desc = '提现审核通知短信';
            $code = '尊敬的有车有保会员'.$info['name'].'，本条短信';
            $content = '成功提现'.$score.'元';
            //发送短信
            $msg = new MessageEntity();
            $tplValue = "#code#=$code&#desc#=$desc&#content#=$content";
            $msg->setMobile($info['mobile']);
            $msg->setTplId("48095");
            $msg->setTplValue($tplValue);
            $ret = (new JuheSms(MessageConfig::getExtraCfg()))->init($msg)->send();
            if($ret['status']){
                return  $this->apiReturnSuc('短信已发送', null, $ret['info']);
            }else{
                return  $this->apiReturnErr($ret['info'], null, $ret['info']);
            }
        }catch (Exception $e){
            Db::rollback();
            return $this->apiReturnErr($e->getMessage());
        }

    }

    /**
     * 否决提现申请
     * @param $apply_id
     * @return array
     */
    public function rejectApply($apply_id)
    {
        $result = $this->getApplyInfo($apply_id);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $apply_info = $result['info'];
        $entity = [
            'apply_status' => 2,
            'update_time' => NOW_TIME
        ];
        $result = $this->saveByID($apply_id, $entity);

        if($result['status']){
            $info = json_decode($apply_info['apply_info'],true);

            $desc = '提现审核通知短信';
            $code = '尊敬的有车有保会员'.$info['name'].'，本条短信';
            $content = '审核不通过';

            //发送短信
            $msg = new MessageEntity();
            $tplValue = "#code#=$code&#desc#=$desc&#content#=$content";
            $msg->setMobile($info['mobile']);
            $msg->setTplId("48095");
            $msg->setTplValue($tplValue);
            $ret = (new JuheSms(MessageConfig::getExtraCfg()))->init($msg)->send();
            if($ret['status']){
                return  $this->apiReturnSuc('短信已发送', null, $ret['info']);
            }else{
                return  $this->apiReturnSuc($ret['info'], null, $ret['info']);
            }
        }else{
            return $this->apiReturnErr($result['info']);
        }
    }

    /**
     * 提现申请列表（全）
     * @param array $page
     * @param int $apply_status
     * @return array
     */
    public function applyList($page = ['curpage'=>1,'size'=>10], $apply_status = 0)
    {
        $map = [
            'apply_status' => $apply_status,
            'status' => 0
        ];

        $order = ['create_time' => 'desc'];

        $result = $this->queryWithCount($map, $page, $order);
        if(!$result['status']) return $this->apiReturnErr($result['info']);
        $info = $result['info'];

        foreach ($info['list'] as &$apply_info){
            //获取提现人信息 个人 平台 商家
            $type = $apply_info['type'];
            $account_id = $apply_info['account_id'];
            $apply_name = '未知';
            switch ($type){
                case AccountEnmu::USER:
                    $map = ['id' => $account_id];
                    $result = (new VUserInfoLogic)->getInfo($map);
                    if(!$result['status']) return $this->apiReturnErr($result['info']);
                    if(empty($result['info'])) return $this->apiReturnErr('error applier');
                    $apply_name = $result['info']['nickname'];
                    break;
                case AccountEnmu::PLATFORM:
                    $result = (new PlatformLogic)->getPlatformInfo($account_id);
                    if(!$result['status']) return $this->apiReturnErr($result['info']);
                    $apply_name = $result['info']['name'];
                    break;
                case AccountEnmu::SELLER:
                    $result = (new SellerLogic)->getSellerInfo($account_id);
                    if(!$result['status']) return $this->apiReturnErr($result['info']);
                    $apply_name = $result['info']['name'];
                    break;
            }
            $apply_info['apply_name'] = $apply_name;
        }

        return $this->apiReturnSuc($info);
    }
}